/*
 * This file is part of Ember.
 *
 * Ember is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Ember is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Ember.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright (C) Grant Tyra 2010
 * granttyra@gmail.com
*/

#include "ember_reflection.h"
#include "ember_object.h"
#include "ember_class.h"
#include "ember_call_stack.h"
#include "ember_types.h"
#include <stdlib.h>

EmberObject *ember_reflection_typeof() {
	EmberObject *obj = EmberCallStackRetrieve("obj");
	EmberClassDef *classdef = obj->classdef;
	return EmberObjectCreateString(classdef->name);
}

EmberObject *ember_reflection_has_attribute() {
	EmberObject *obj = EmberCallStackRetrieve("obj");
	EmberObject *name_obj = EmberCallStackRetrieve("name");
	char *name = EmberStringValue(name_obj);
	EmberObject *attr = EmberObjectGetAttribute(obj, name);
	return EmberObjectCreateInteger(attr != NULL);
}

EmberObject *ember_reflection_has_method() {
	EmberObject *obj = EmberCallStackRetrieve("obj");
	EmberObject *name_obj = EmberCallStackRetrieve("name");
	char *name = EmberStringValue(name_obj);
	EmberMethod *method = EmberClassGetInstanceMethod(obj->classdef, name);
	return EmberObjectCreateInteger(method != NULL);
}

void ember_reflection_install() {
	EmberClassDef *classdef = EmberClassCreate("Reflect", NULL);
	EmberClassAddStaticMethod(classdef, "typeOf", EmberMethodCreate("obj", 1, ember_reflection_typeof));
	EmberClassAddStaticMethod(classdef, "hasAttribute", EmberMethodCreate("obj, name", 1, ember_reflection_has_attribute));
	EmberClassAddStaticMethod(classdef, "hasMethod", EmberMethodCreate("obj, name", 1, ember_reflection_has_method));
	EmberClassMapPut(classdef);
}
